﻿using System.Collections.Generic;
using EnergyService_CSharp;
using System.Diagnostics;
using System.Data;
using System;

namespace DatabasePlugin
{
    public class EnergyReadingRepository
    {
        private IDbConnection dbConn;
        private IDbCommand dbCmd;
        private const string InsertSql = "INSERT INTO EnergyReadings ([TimeStamp], [Temperature], [Energy]) VALUES ('{0}', '{1}', '{2}')";

        public EnergyReadingRepository(string dbType, string connString)
        {
            dbConn = DbTypeFactory.GetDbConnection(dbType);
            dbConn.ConnectionString = connString;

            dbCmd = DbTypeFactory.GetDbCommand(dbType);
        }

        public bool Save(EnergyReading rdg)
        {
            string sql = string.Format(InsertSql, rdg.TimeStamp.ToString("yyyy:MM:dd hh:mm:ss"), rdg.Temperature, rdg.Energy);
            try
            {
                dbCmd.CommandText = sql;
                dbConn.Open();
                dbCmd.Connection = dbConn;
                dbCmd.ExecuteNonQuery();
                dbConn.Close();
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                if (dbConn.State != ConnectionState.Closed)
                {
                    dbConn.Close();
                }
                return false;
            }
        }

        // useful for future - maybe
        public bool Save(IEnumerable<EnergyReading> energyReadings)
        {
            bool allOk = true;
            foreach (var energyReading in energyReadings)
            {
                allOk = (allOk && Save(energyReading));
            }
            return allOk;
        }

    }
}